package com.accloud.cloudservice;

import com.accloud.service.ACException;
import com.accloud.utils.Crc16Util;
import java.nio.ByteBuffer;
import org.java_websocket.drafts.Draft_75;

/* access modifiers changed from: package-private */
public class LocalMessage {
    public final int msgCode;
    public byte msgId;
    public byte optNum;
    public final byte[] payload;
    public final int totalMsgCrc;
    public byte version;

    public LocalMessage(int msgCode2, byte[] payload2) {
        this((byte) 0, msgCode2, (byte) 0, (byte) 0, payload2);
    }

    private LocalMessage(byte version2, int msgCode2, byte msgId2, byte optNum2, byte[] payload2) {
        int i = 0;
        this.version = 0;
        this.msgId = 0;
        this.optNum = 0;
        this.version = version2;
        this.msgCode = msgCode2;
        this.msgId = msgId2;
        this.optNum = optNum2;
        this.payload = payload2;
        this.totalMsgCrc = payload2 != null ? Crc16Util.GetCrc16(payload2, payload2.length) : i;
    }

    public byte[] toBytes() {
        int length = this.payload != null ? this.payload.length : 0;
        ByteBuffer buffer = ByteBuffer.allocate(length + 8).put(this.version).put(this.msgId).put((byte) this.msgCode).put(this.optNum).putShort((short) length).putShort((short) this.totalMsgCrc);
        if (this.payload != null) {
            buffer.put(this.payload);
        }
        return buffer.array();
    }

    public static LocalMessage fromBytes(byte[] bytes) throws ACException {
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        byte version2 = buffer.get();
        byte msgId2 = buffer.get();
        int msgCode2 = buffer.get() & Draft_75.END_OF_FRAME;
        byte optNum2 = buffer.get();
        int payloadLength = buffer.getShort() & 65535;
        int totalMsgCrc2 = buffer.getShort() & 65535;
        byte[] payload2 = new byte[payloadLength];
        buffer.get(payload2);
        if (Crc16Util.GetCrc16(payload2, payload2.length) == totalMsgCrc2) {
            return new LocalMessage(version2, msgCode2, msgId2, optNum2, payload2);
        }
        throw new ACException(ACException.INTERNAL_ERROR, "Local message fail CRC check");
    }
}
